package com.imay.live.manager;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.proto.Result;
import com.imay.live.proto.account.QiniuCdnGetTokenResp;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * 七牛上传工具类
 * Created by chan on 2017/4/1.
 */
public class UploadFileManager {
    private static UploadFileManager instance;

    public static final String BASEURL = "http://img.imay.com/";

    private final String TYPESTRHEAD = "head";
    private final String TYPESTRPIC = "pic";
    private final String TYPESTRVIDEO = "video";

    public synchronized static UploadFileManager getInstance() {
        if (instance == null) {
            instance = new UploadFileManager();
        }
        return instance;
    }

    private final UploadManager uploadManager;

    private UploadFileManager() {
        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(10) // 服务器响应超时。默认60秒
                .retryMax(0)
                //.recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    /**
     * 上传头像
     *
     * @param filePath
     * @param uploadCallBack
     */
    public void uploadHead(final String filePath, UploadCallBack uploadCallBack) {
        upload(filePath, 1, uploadCallBack);
    }

    /**
     * 上传图片
     *
     * @param filePath
     * @param uploadCallBack
     */
    public String uploadPic(final String filePath, UploadCallBack uploadCallBack) {
        return upload(filePath, 2, uploadCallBack);
    }

    /**
     * 上传视频
     *
     * @param filePath
     * @param uploadCallBack
     */
    public void uploadVideo(final String filePath, UploadCallBack uploadCallBack) {
        upload(filePath, 3, uploadCallBack);
    }

    /**
     * 七牛图片上传
     *
     * @param filePath 途径
     * @param type     1、头像 2、图片 3、视频
     */
    private String upload(final String filePath, final int type, final UploadCallBack uploadCallBack) {
        long uid = AccountManager.getInstance().getUid();
        int numcode = (int) ((Math.random() * 9 + 1) * 1000);
        final String name = getTypeStr(type) + "-" + uid + "-" + System.currentTimeMillis() / 1000L + "-" + numcode + getFileProfix(type);
        ProtoRequestHelper.task(ProtoHttpFactory.qiniuGetToken("imayimg")).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<QiniuCdnGetTokenResp> result = JSON.parseObject(data, new TypeReference<Result<QiniuCdnGetTokenResp>>() {
                }.getType());
                if (result.result == CodeSuccess) {
                    QiniuCdnGetTokenResp resp = result.data;
                    final String token = resp.token;
                    final String key = name;
                    uploadManager.put(filePath, key, token, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            if (info.isOK()) {
                                String resultUrl = UploadFileManager.BASEURL + key;
                                if (uploadCallBack != null) {
                                    uploadCallBack.uploadSuccess(resultUrl);
                                }
                            } else {
                                if (uploadCallBack != null) {
                                    uploadCallBack.uploadFailer(info.statusCode, info.error);
                                }
                            }
                        }
                    }, null);
                } else {
                    if (uploadCallBack != null) {
                        uploadCallBack.uploadFailer(result.result, result.errorDesc);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if(uploadCallBack != null){
                    uploadCallBack.uploadFailer(code, message);
                }
            }
        });
        return UploadFileManager.BASEURL + name;
    }

    /**
     * 回调
     */
    public interface UploadCallBack {
        /**
         * 成功
         *
         * @param fileUrl
         */
        void uploadSuccess(String fileUrl);

        /**
         * 失败
         *
         * @param errorCode
         * @param errorMessage
         */
        void uploadFailer(int errorCode, String errorMessage);
    }

    /**
     * 获取类型
     *
     * @param type
     * @return
     */
    private String getTypeStr(int type) {
        if (type == 1) {
            return TYPESTRHEAD;
        } else if (type == 2) {
            return TYPESTRPIC;
        } else if (type == 3) {
            return TYPESTRVIDEO;
        }
        return "";
    }

    /**
     * 获取后缀
     *
     * @param type
     * @return
     */
    private String getFileProfix(int type) {
        if (type == 1) {
            return ".jpg";
        } else if (type == 2) {
            return ".jpg";
        } else if (type == 3) {
            return ".mp4";
        }
        return "";
    }
}
